import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export interface dimms {
  id: string;
  health: string;
  partNumber: number;
  serialNumber: string;
  statusState: string;
  sparePartNumber: string;
  description: string;
  memoryType: string;
  memorySize: string;
  identifyLed: string;
  uri: string;
  locationNumber: string;
  operatingSpeedMhz: number;
  manufacturer: string;
}

export const useMemoryStore = defineStore('MemoryStore', () => {
  const dimms = ref([] as dimms[]);
  const setMemoryInfo = (data: { data: any }[]) => {
    dimms.value = data.map(({ data }) => {
      const {
        Id,
        Status = {},
        PartNumber,
        SerialNumber,
        SparePartNumber,
        Description,
        MemoryType,
        CapacityMiB,
        LocationIndicatorActive,
        Location,
        OperatingSpeedMhz,
        Manufacturer,
      } = data;
      return {
        id: Id,
        health: Status.Health,
        partNumber: PartNumber,
        serialNumber: SerialNumber,
        statusState: Status.State,
        sparePartNumber: SparePartNumber,
        description: Description,
        memoryType: MemoryType,
        memorySize: CapacityMiB,
        identifyLed: LocationIndicatorActive,
        uri: data['@odata.id'],
        locationNumber: Location?.PartLocation?.ServiceLabel,
        operatingSpeedMhz: OperatingSpeedMhz,
        manufacturer: Manufacturer,
      };
    });
  };
  const getDimms = async () => {
    return await api
      .get('/redfish/v1/Systems/system/Memory')
      .then(({ data: { Members } }) => {
        const promises = Members.map((item: { [x: string]: string }) =>
          api.get(item['@odata.id']),
        );
        return api.all(promises);
      })
      .then((response) => setMemoryInfo(response as { data: any }[]))
      .catch((error) => console.log(error));
  };
  const updateIdentifyLedValue = async (led: {
    uri: any;
    identifyLed: any;
  }) => {
    const uri = led.uri;
    const updatedIdentifyLedValue = {
      LocationIndicatorActive: led.identifyLed,
    };
    return await api.patch(uri, updatedIdentifyLedValue).catch((error) => {
      getDimms();
      console.log('error', error);
      if (led.identifyLed) {
        throw new Error(
          t('pageInventory.toast.errorEnableIdentifyLed') as string,
        );
      } else {
        throw new Error(
          t('pageInventory.toast.errorDisableIdentifyLed') as string,
        );
      }
    });
  };
  return { dimms, setMemoryInfo, getDimms, updateIdentifyLedValue };
});
